import { ref,InjectionKey } from "vue"
import { createStore,Store,useStore as baseUseStore } from "vuex"
import api from "@/api/index"
import { localCache,sessionCache } from "@/utils/cache"

//为store的state声明类型
export interface StateTypes{
  count:number,
  language:any,
  lang:any,
  loginUser:any,
  registerMobile:number
}

//定义injectionKey,Symbol表示注释/描述，key抛出注册到main.ts
export const key:InjectionKey<Store<StateTypes>>=Symbol('storeKey')

export function useStore(){
  return baseUseStore(key)
}

export const store=createStore<StateTypes>({
  state:{ //状态
    count:0,
    language:null,//全局语言状态
    lang:null,//语言
    loginUser:null,//登录用户
    registerMobile:0,
  },
  mutations:{ //同步方法，事件处理状态
    setCount(state:any,payload:any){//参数payload-自定义
      state.count+=payload
      return state.count
    },
    setLanguage(state:any,payload:any,lan:any){
      state.language=payload
      state.lang=lan
      localCache.setCache('userLang',payload)

      // ** TODO ** 这里缓存和state都存不了language
      // state.lang=lan
      // localCache.setCache('lang',lan)
      return state.language
    },
    setLoginUser(state:any,payload:any){
        console.log("payload-----",payload)
        state.loginUser=payload
        return state.loginUser
    },
    setRegiter(state:any,payload:any){
        state.registerMobile=payload
        return state.registerMobile
    }
  },
  actions:{
    //提取state参数(【context上下文，具有与store实例相同的方法和属性，可以使用.commit、.state...】，【payload传入的参数】)
    fetchCount(context:any,payload:any){//参数context-上下文
      setTimeout(()=>{
        context.commit('setCount',payload)
      },1000)
    },
    //保存全局语言
    saveLanguage(context:any,payload:any,lan:any){
      api.saveLan(payload).then((res:any)=>{
        console.log("保存全局语言响应：",res)
        if(res.responseData?.length){
          console.log("保存语言成功")
          context.commit('setLanguage',payload,lan)
        }
      })
    }
  },
  getters:{},
  modules:{},
  strict:true,
})